/*
 * Copyright (C) 2023 Coder.AN
 * Email: an.hongjun@foxmail.com
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
#include "edge_os.h"

std::vector<os::FileInfo> os::listdir(char* target_dir)
{
    std::vector<FileInfo> res;
    DIR *dir = opendir(target_dir);
    if(dir == nullptr) {
        std::cerr << "Error opening directory " << target_dir << std::endl;
        return res;
    }
    struct dirent *entry;
    while((entry = readdir(dir)) != nullptr) {
        if(entry->d_type == DT_REG) {
            std::string path = std::string(target_dir) + "/" + std::string(entry->d_name);
            struct stat st;
            if(stat(path.c_str(), &st) != 0) {
                std::cerr << "Error getting file status for " << path << std::endl;
                continue;
            }
            FileInfo new_file;
            new_file.file_name = std::string(entry->d_name);
            new_file.file_size = st.st_size;
            res.push_back(new_file);
        }
    }
    closedir(dir);
    return res;
}

std::vector<char> os::read_binary_file(const char* path)
{
    std::ifstream file(path, std::ios::binary);

    if (!file) {
        std::cout << "Failed to open file!" << std::endl;
        std::vector<char> empty_vector;
        return empty_vector;
    }

    file.seekg(0, std::ios::end);
    std::streampos fileSize = file.tellg();
    file.seekg(0, std::ios::beg);

    std::vector<char> buffer(fileSize);

    file.read(buffer.data(), fileSize);
    file.close();

    return buffer;
}

bool os::write_binary_file(const char* path, uint8_t* buffer, size_t size)
{
    std::ofstream outf(path, std::ios::binary);
    outf.write((char*)buffer, size);
    outf.close();
    return true;
}
